// 名字是否重复
import article from "@src/models/article";
import {Request} from "express";
import moment from "moment";
import {getID} from "@src/util/util";
import Constant from "@src/util/constant";
import {Op} from "sequelize";
import File from "@src/models/file";
import Dict from "@src/models/dict";
import dictSql from "@src/sql/dictSql";

// 名称是否重复
const isArticleName = async (name: string) => {
  return await article.findOne({
    where: {
      name,
    },
  });
};

// 是否存在文章id
const isArticleId = async (id: string) => {
  return await article.findOne({
    where: {
      id,
    },
  });
};

// 添加文章
const add = async (req: Request) => {
  await article.create({
    ...req.body,
    created_at: moment().format("X"),
    id: getID(),
    recommend: 0,
    grounding: 0,
    visit_num: 0,
  });
  return Constant.DEFAULT_SUCCESS;
};

// 刪除文章
const _delete = async (id: string) => {
  await article.destroy({
    where: {
      id,
    },
  });
};

// 更新文章
const update = async (req: Request) => {
  await article.update(
    {
      ...req.body,
      updated_at: moment().format("X"),
    },
    {
      where: {
        id: req.params.id,
      },
    },
  );
};

// 文章列表
const list = async (offset: number, limit: number, filters: { name?: string, grounding?: string, category_id: string }) => {
  let whereObj: any = {};
  for (const v in filters) {
    if (v === "name" && filters[v]) {
      whereObj[v] = {
        [Op.substring]: filters[v],
      };
    }
    if (v === "grounding" && filters[v]) {
      whereObj[v] = filters[v];
    }
    if (v === "category_id" && filters[v]) {
      whereObj[v] = filters[v];
    }
  }
  // 查询字典分类id
  const dictData: any = await dictSql.getTypeId(<string>filters['category_id']);

  const {count, rows} = await article.findAndCountAll({
    attributes: ["id", "name", "username", "recommend", "grounding", "visit_num", "category_id", "region_id"],
    where: whereObj,
    offset,
    limit,
    include: [
      {
        attributes: ["id", "size", "type", "path"],
        model: File,
        // 指定别名
        as: "cover",
      },
      {
        attributes: ["type_id", "name"],
        model: Dict,
        as: "dict",
      },
    ],
  });
  return {count, rows, dictData};
};

// 更新首页推荐
const updateRecommend = async (id: string, recommend: number) => {
  await article.update({
    recommend,
    updated_at: moment().format("X"),
  }, {
    where: {
      id,
    },
  });
  return Constant.DEFAULT_SUCCESS;
};

// 是否上架
const updateGrounding = async (id: string, grounding: number) => {
  await article.update({
    grounding,
    updated_at: moment().format("X"),
  }, {
    where: {
      id,
    },
  });
  return Constant.DEFAULT_SUCCESS;
};

const detail = async (id: string) => {
  const data = await article.findOne({
    attributes: ["id", "name", "username", "recommend", "grounding", "visit_num", "category_id", "content", "created_at"],
    where: {
      id,
    },
    include: [
      {
        attributes: ["id", "size", "type", "path"],
        model: File,
        // 多个关联外键同时查询
        all: true,
      },
      {
        attributes: ["type_id", "name"],
        model: Dict,
        as: "dict",
      },
    ],
  });
  return {
    ...Constant.DEFAULT_SUCCESS,
    data,
  };
};

// 前台
const frontList = async (offset: number, limit: number, id: string,filters:{name?:string}) => {
  let whereObj: any = {};
  for (const v in filters) {
    if (v === "name" && filters[v]) {
      whereObj[v] = {
        [Op.substring]: filters[v],
      };
    }
  }
  const {count, rows} = await article.findAndCountAll({
    attributes: ["id", "name", "username", "recommend", "grounding", "visit_num", "category_id", "region_id"],
    where: {
      category_id: id,
      ...whereObj
    },
    offset,
    limit,
    include: [
      {
        attributes: ["id", "size", "type", "path"],
        model: File,
        // 指定别名
        as: "cover",
      },
      {
        attributes: ["type_id", "name"],
        model: Dict,
        as: "dict",
      },
    ],
  });
  return {count, rows};
};

const recommend = async () => {
  const data = await article.findAll({
    attributes: ["id", "name"],
    where: {
      recommend: 1,
    },
    include: [
      {
        attributes: ["id", "size", "type", "path"],
        model: File,
        // 指定别名
        as: "cover",
      },
    ],
  });
  return {
    data,
    ...Constant.DEFAULT_SUCCESS,
  };
};

// 排名
const ranking = async ()=>{
  const data = await article.findAndCountAll({
    attributes: ["id", "name", "visit_num"],
    offset: 0,
    limit: 7,
    order: [
      ['visit_num', 'DESC'],
    ],
  });
  return {
    data,
    ...Constant.DEFAULT_SUCCESS,
  };
}

export default {
  isArticleName,
  add,
  isArticleId,
  _delete,
  update,
  list,
  updateRecommend,
  updateGrounding,
  detail,
  frontList,
  recommend,
  ranking
};